package com.sdx.console.person.web;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.ibeetl.admin.console.service.OrgConsoleService;
import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.entity.BaseEntity;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.service.CorePlatformService;
import com.ibeetl.admin.core.util.DateUtil;
import com.ibeetl.admin.core.util.ValidateConfig;
import com.ibeetl.admin.core.web.AuthorizedBaesController;
import com.ibeetl.admin.core.web.JsonResult;
import com.ibeetl.admin.core.web.JsonReturnCode;
import com.sdx.common.entity.ResCloudFile;
import com.sdx.common.service.ResCloudFileService;
import com.sdx.common.utils.FileUtils;
import com.sdx.common.utils.JacksonUtils;
import com.sdx.console.customer.entity.CustomerInfo;
import com.sdx.console.customer.service.CustomerInfoService;
import com.sdx.console.person.entity.CustomerExtInfo;
import com.sdx.console.person.service.CustomerExtInfoService;
import com.sdx.service.ConfigService;
import com.sdx.third.AliOSSApi;
import org.apache.commons.lang3.StringUtils;
import org.beetl.sql.core.engine.PageQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * 老师 接口
 */
@RequestMapping("/person/customerExtInfo")
@Controller
public class CustomerExtInfoController extends AuthorizedBaesController{
	private static final Logger log = LoggerFactory.getLogger(CustomerExtInfoController.class);
    private static final String MODEL = "/person/customerExtInfo";


    @Resource
	private CustomerExtInfoService customerExtInfoService;
    
    @Resource
    private ResCloudFileService resCloudFileService;

    @Resource
    private CustomerInfoService customerInfoService;

	@Resource
	private CorePlatformService platformService;

	@Resource
	private OrgConsoleService orgConsoleService;

    /* 页面 */


	/**
	 * 初始化编辑页面
	 *
	 * @param view
	 */
	private void initEditPage(ModelAndView view,HttpServletRequest request) {
		CustomerInfo customerInfo = new CustomerInfo();
		customerInfo.setIsTeacher(1);
		List<CustomerInfo> customerInfoList =  customerInfoService.template(customerInfo);
		view.addObject("customerInfoList",customerInfoList);
		Integer accessType = platformService.getAccessType(request);
		view.addObject("accessType",accessType);
		view.addObject("orgList",orgConsoleService.getOrgs());
		CoreUser user = getLoginUser(request);
		Long orgId = null;
		if(accessType!=null&&accessType.intValue()== 3 ){
			orgId = user.getOrgId();
		}
		view.addObject("orgId",orgId);
		//resTagList
	}



    @GetMapping("/index.do")
    @Function("person.customerExtInfo.query")
    @ResponseBody
    public ModelAndView index(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/index.html") ;
		initEditPage(view,request);
        return view;
    }

	@GetMapping("/indexTeacher.do")
	@ResponseBody
	public ModelAndView indexTeacher(HttpServletRequest request) {
		ModelAndView view = new ModelAndView(MODEL+"/teacher.html") ;
		initEditPage(view,request);
		return view;
	}

    @GetMapping("/edit.do")
    @Function("person.customerExtInfo.edit")
    @ResponseBody
    public ModelAndView edit(String customerId,HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
		initEditPage(view,request);
	    CustomerInfo customerInfo = customerInfoService.queryById(customerId);
	    view.addObject("customerInfo",customerInfo);
		CustomerExtInfo customerExtInfo = customerExtInfoService.queryById(customerId);
		customerExtInfo.setCustomerName(customerInfo.getCustomerName());
		view.addObject("customerExtInfo", customerExtInfo);
		try {
			view.addObject("customerExtInfoJson", JacksonUtils.toJsonString(customerExtInfo,JacksonUtils.DF1));
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
        return view;
    }

    @GetMapping("/add.do")
    @Function("person.customerExtInfo.add")
    @ResponseBody
    public ModelAndView add(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
		initEditPage(view,request);
        return view;
    }

    /* ajax json */

    @PostMapping("/list.json")
    @Function("person.customerExtInfo.query")
    @ResponseBody
    public JsonResult<PageQuery> list(CustomerExtInfo condtion,HttpServletRequest request)
    {
		Integer accessType = platformService.getAccessType(request);
		CoreUser user = getLoginUser(request);
		if (accessType.intValue()==1) {
			String customerId = customerInfoService.getCustomerId(user.getId().intValue());
			if(StringUtils.isBlank(customerId)){
				customerId = "#";
			}
			condtion.setCustomerId(customerId);
		}
		if(accessType.intValue()== 3 ){
			condtion.setOrgId(user.getOrgId());
		}
        PageQuery page = condtion.getPageQuery();
	    page.setOrderBy("updated_time desc,customer_id");
        customerExtInfoService.queryByCondition(page);
        return JsonResult.success(page);
    }

    private JsonResult save(boolean isNew,CustomerExtInfo customerExtInfo,HttpServletRequest request
							,MultipartFile workPicurlFile
							,MultipartFile dailyPicurlFile
	) {
    	JsonResult result = JsonResult.success();
		String dir = DateUtil.now("yyyyMMdd");
    	String subPath = "/images/teacher/"+dir+"/";
		String bucketName = "sdxcomm";
		if (!FileUtils.isEmptyFile(workPicurlFile)) {
			try
			{
		        String workPicurlFileNamePair = FileUtils.upload(subPath,workPicurlFile);
		        String workPicurlStoreFile = workPicurlFileNamePair.split("::")[0];
		        workPicurlStoreFile = subPath+workPicurlStoreFile;
				AliOSSApi.uploadLocalFile(FileUtils.getRoot()+workPicurlStoreFile,bucketName,workPicurlStoreFile.substring(1));
				String workPicurlUrl = "https://sdxcomm."+ ConfigService.ossDomain+workPicurlStoreFile;
				customerExtInfo.setWorkPicurl(workPicurlUrl);
				resCloudFileService.insertResFile(ResCloudFile.ALI,workPicurlStoreFile,workPicurlUrl,"a","老师工作照");
			}catch(Exception e) {
				e.printStackTrace();
				result.setCode(JsonReturnCode.IO_ERROR.getCode());
				result.setMsg("新增服务老师失败，请检查是否已经存在！");
			}
		}
		if (!FileUtils.isEmptyFile(dailyPicurlFile)) {
			try
			{
		        String dailyPicurlFileNamePair = FileUtils.upload(subPath,dailyPicurlFile);
		        String dailyPicurlStoreFile = dailyPicurlFileNamePair.split("::")[0];
		        dailyPicurlStoreFile = subPath+dailyPicurlStoreFile;
				AliOSSApi.uploadLocalFile(FileUtils.getRoot()+dailyPicurlStoreFile,bucketName,dailyPicurlStoreFile.substring(1));
				String dailyPicurlUrl = "https://sdxcomm."+ConfigService.ossDomain+dailyPicurlStoreFile;
				customerExtInfo.setDailyPicurl(dailyPicurlUrl);
				resCloudFileService.insertResFile(ResCloudFile.ALI,dailyPicurlStoreFile,dailyPicurlUrl,"a","老师工作照");
			}catch(Exception e) {
				e.printStackTrace();
				result.setCode(JsonReturnCode.IO_ERROR.getCode());
				result.setMsg("新增服务老师失败，图片上传失败！");
			}
		}
		CoreUser user = getLoginUser(request);
		customerExtInfo.setUpdatedBy(user.getId().intValue());
		customerExtInfo.setUpdatedName(user.getName());
		customerExtInfo.setUpdatedTime(new Date());

    	if (isNew) {
			customerExtInfoService.save(customerExtInfo);
			CustomerInfo customerInfo = new CustomerInfo();
			customerInfo.setCustomerId(customerExtInfo.getCustomerId());
			customerInfo.setIsTeacher(1);
			customerInfo.setUpdatedBy(user.getId().intValue());
			customerInfo.setUpdatedName(user.getName());
			customerInfo.setUpdatedTime(new Date());
			customerInfoService.updateTemplate(customerInfo);

		} else {
			customerExtInfoService.updateTemplate(customerExtInfo);
		}
		return result;
	}
    @PostMapping("/add.json")
    @Function("person.customerExtInfo.add")
    @ResponseBody
    public JsonResult add(@Validated(ValidateConfig.ADD.class)CustomerExtInfo customerExtInfo,HttpServletRequest request
							,@RequestParam("workPicurlFile") MultipartFile workPicurlFile
							,@RequestParam("dailyPicurlFile") MultipartFile dailyPicurlFile
		)
    {

        return save(true,customerExtInfo,request
					,workPicurlFile
					,dailyPicurlFile
		);
    }

    @PostMapping("/update.json")
    @Function("person.customerExtInfo.edit")
    @ResponseBody
    public JsonResult<String> update(@Validated(ValidateConfig.UPDATE.class)  CustomerExtInfo customerExtInfo,HttpServletRequest request
							,@RequestParam("workPicurlFile") MultipartFile workPicurlFile
							,@RequestParam("dailyPicurlFile") MultipartFile dailyPicurlFile
		) {
		return save(false,customerExtInfo,request
		,workPicurlFile
		,dailyPicurlFile
		);
    }


   
    @GetMapping("/view.json")
    @Function("person.customerExtInfo.query")
    @ResponseBody
    public JsonResult<CustomerExtInfo>queryInfo(String customerId) {
        CustomerExtInfo customerExtInfo = customerExtInfoService.queryById( customerId);
        return  JsonResult.success(customerExtInfo);
    }

    @PostMapping("/delete.json")
    @Function("person.customerExtInfo.del")
    @ResponseBody
    public JsonResult delete(String ids) {
        if (ids.endsWith(",")) {
            ids = StringUtils.substringBeforeLast(ids, ",");
        }
        //List<Long> idList = ConvertUtil.str2longs(ids);
		List<String> idList = new ArrayList<String>();
		Collections.addAll(idList,ids.split(","));
        customerExtInfoService.batchDelCustomerExtInfo(idList);
        return JsonResult.success();
    }

	@PostMapping("/getTeacher.json")
	@ResponseBody
	public JsonResult getTeacher(Integer orgId) {
		List<CustomerInfo> list = new ArrayList<>();
		list = customerExtInfoService.selectTeacher(orgId);
		return JsonResult.success(list);
	}
    

}
